#!/usr/bin/env bash

## Util Methods:
function displayMessage() {
    whiptail --title "$1" --msgbox "$2" 8 78
}


function main() {
need_password=1
while true; do
     if [ $need_password == 1 ]; then
	passwordDemo
     else 	
        demo=$(whiptail --title "CocoTUI" --ok-button "Select" --cancel-button "Quit" --menu "Select an option" 20 78 10 \
	    "1" "Change Password" \
	    "2" "Configure Management Network" \
	    "3" "Test Management Network" \
	    "4" "Show Management Network" \
	    "5" "Enter Shell" \
            3>&1 1>&2 2>&3)

        exitstatus=$?

        if [ ${exitstatus} = 0 ]; then
            case ${demo} in
                1)
                    change_pwd 
                ;;
                2)
                   change_mgmt 
                ;;
                3)
                    test_mgmt
                ;;
                4)
                    show_mgmt 
                ;;
		5)
		    enter_shell 
		;;
            esac
        else
            exit
        fi
      fi
    done
}

function messageBoxDemo() {
    whiptail --title "Message Box Demo" --msgbox "This is an example of a message box. You must hit OK to continue." 8 78
}

function change_pwd() {
    PASSWORD=$(whiptail --title "Enter Password" --passwordbox "Please enter your secret password" 8 78 3>&1 1>&2 2>&3)

    PWD=$(whiptail --title "Enter Password Again" --passwordbox "Please enter your secret password" 8 78 3>&1 1>&2 2>&3)
    if [ $PASSWORD != $PWD ]; then
         whiptail --title "Change Result" --msgbox "The passwords you entered not the same ${COLOR}, request canceled." 8 78
    else
	 mkdir -p /opt/tfw
	 in=$( base64 <<< "$PASSWORD")
	 echo $in  > /opt/tfw/pwd.txt
         whiptail --title "Change Result" --msgbox "Password changed. ${COLOR}" 8 78
    fi

}
function inputBoxDemo() {
    COLOR=$(whiptail --inputbox "What is your favorite Color?" 8 78 Blue --title "Example Dialog" 3>&1 1>&2 2>&3)
    exitstatus=$?
    if [ ${exitstatus} = 0 ]; then
        whiptail --title "Input Box Results" --msgbox "You selected Ok and entered ${COLOR}" 8 78
    else
        whiptail --title "Input Box Results" --msgbox "You selected Cancel" 8 78
    fi
}
function valid_ip()
    {
        local ip=$1
        local stat=1
        if [[ $ip =~ '^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$' ]]; then
        OIFS=$IFS
        IFS='.'
        ip=($ip)
        IFS=$OIFS
        [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
        stat=$?
        fi
        return $stat
    }
function set_ip()  
{  
    cp -r $ifcfg ${ifcfg}.bak  
    echo -ne "DEVICE=eth0  
    BOOTPROTO=static 
    HWADDR=$mac  
    IPADDR=$ipadd  
    NETMASK=$netmask  
    ONBOOT=yes  
    " > $ifcfg  
    echo "IPaddress set Success!" 
} 
function set_gw()
{
    cp -r $network ${network}.bak
    echo -ne "NETWORKING=yes
    NETWORKING_IPV6=no
    HOSTNAME=`hostname`
    GATEWAY=$gateway
    " > $network
    echo "Netmask set Success!"
}
function set_dns()
{
    cp -r $resolv ${resolv}.bak
    echo -e "nameserver $dns" > $resolv
    echo "DNS set Success!"
}

function cdr2mask ()
{
   # Number of args to shift, 255..255, first non-255 byte, zeroes
   set -- $(( 5 - ($1 / 8) )) 255 255 255 255 $(( (255 << (8 - ($1 % 8))) & 255 )) 0 0 0
   [ $1 -gt 1 ] && shift $1 || shift
   echo ${1-0}.${2-0}.${3-0}.${4-0}
}
function show_mgmt() {
    interface="enp2s0"
    ipaddr=$(ip a show dev $interface|grep -w inet|awk '{print $2}'|awk -F '/' '{print $1}')
    masklen=$(ip a show dev $interface|grep -w inet|awk '{print $2}'|awk -F '/' '{print $2}')
    netmask=$(cdr2mask $masklen)
    gateway=$(route -n | grep $interface | grep UG | awk '{print $2}')
    displayMessage "Show Results" "INTERFACE : $interface\nIPADDR : $ipaddr NETMASK: $netmask GATEWAY: $gateway\n"

}
function change_mgmt() {
    interface="enp2s0"
    ipaddr=$(ip a show dev $interface|grep -w inet|awk '{print $2}'|awk -F '/' '{print $1}')
    masklen=$(ip a show dev $interface|grep -w inet|awk '{print $2}'|awk -F '/' '{print $2}')
    netmask=$(cdr2mask $masklen)
    gateway=$(route -n | grep $interface | grep UG | awk '{print $2}')
    ipaddr=$(whiptail --inputbox "New IP Address?" 8 78 $ipaddr  --title "Management IP Config Dialog" 3>&1 1>&2 2>&3)
    gateway=$(whiptail --inputbox "IP Gateway?" 8 78 $gateway  --title "Management IP Config Dialog" 3>&1 1>&2 2>&3)
    netmask=$(whiptail --inputbox "IP Gateway?" 8 78 $netmask  --title "Management IP Config Dialog" 3>&1 1>&2 2>&3)

    exitstatus=$?
    if [ ${exitstatus} = 0 ]; then
        whiptail --title "Input Box Results" --msgbox "IP address entered." 8 78
	#+++++定义一些变量+++++
ifcfg=/etc/sysconfig/network-scripts/ifcfg-eth0
mac=`grep -i HWADDR $ifcfg|awk -F "=" '{print $2}'`
echo "mac is $mac"
#resolv=/etc/resolv.conf
network=/etc/sysconfig/network
#+++++++++++++++++++++++++++++++++++++++++++++++
#1.对脚本选项进行分析，是否有指定ip地址？如果没有指定ip地址选项则#保持当前ip地址不变，如果当前并未设置ip地址，则提示必须指定ip地址#选项并退出脚本；
#2.同上对子网掩码进行判断；
#3.同上对默认网关进行判断；
#+++++++++++++++++++++++++++++++++++++++++++++++
if [ ! $ipadd ];then
    ipadd=`/sbin/ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6|awk '{print $2}'|tr -d "addr:"`
    if [ ! $ipadd ];then
     echo "There are currently no ip,Please use '-i' option specified IPaddress"
    fi
fi
if [ ! $netmask ];then
    echo "Use the current netmask"
    netmask=`/sbin/ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6|awk '{print $4}'|tr -d "Mask:"`
    if [ ! $netmask ];then
     echo "The current netmask does not exist Re-run the specified '-n' option or Use the default netmask:255.255.255.0"
     netmask="255.255.255.0"
     echo "IP set:$ipadd NETMASK set:$netmask"
    fi
else
    echo "IP set:$ipadd NETMASK set:$netmask"
fi
if [ ! $gateway ];then
    echo "Use the current gateway"
    gateway=`route|grep default|awk '{print $2}'`
    if [ ! $gateway ];then
     gateway=`echo $ipadd|cut -d. -f1-3`
     gateway=${gateway}.1
     echo "Using the default gateway $gateway "
    fi
else
    echo "Gateway set:$gateway"
fi
#+++++判断是否指定设置dns选项，若指定则修改dns，未指定则不修改；
if [ $dns ];then
    echo "DNS set:$dns"
    #set_dns
fi
#+++++设置ip地址及子网掩码+++++
set_ip
#++++设置默认网关+++++
set_gw
#+++++重启网络服务+++++
service network restart >/dev/null
#+++++输出设置的ip地址+++++
echo "IPADDRESS:$ipadd"
#+++++输出设置的子网掩码+++++
echo "NETMASK:$netmask"
#+++++输出设置的默认网关+++++
echo "GATEWAY:$gateway"
#+++++输出设置OK信息+++++
echo "Set OK!"
    else
        whiptail --title "Input Box Results" --msgbox "You selected Cancel" 8 78
    fi
}

function test_mgmt() {
	    HOSTS=$(whiptail --inputbox "Which IP/hostname do you want to ping?" 8 78 www.coconet.cn --title "Ping Test Dialog" 3>&1 1>&2 2>&3)
    exitstatus=$?
    if [ ${exitstatus} = 0 ]; then
    

# no ping request
COUNT=1

# email report when
SUBJECT="Ping failed"
for myHost in $HOSTS
do
  count=$(ping -c $COUNT $myHost | grep 'received' | awk -F',' '{ print $2 }' | awk '{ print $1 }')
  if [ ! -n $count ]; then
     displayMessage "Ping Results" "Host : $myHost is down (ping failed) at $(date)"
  elif [ $count -eq 0 ]; then
    # 100% failed
     displayMessage "Ping Results" "Host : $myHost is down (ping failed) at $(date)" 
  else
     displayMessage "Ping Results" "Host : $myHost is up (ping success) at $(date)"

  fi
done
fi
}

function yesNoDemo() {

    if (whiptail --title "Yes/No Demo" --yesno "This is an example of a yes/no box." 8 78) then
        displayMessage "Yes/No Box Results" "User selected Yes, exit status was $?"
    else
        displayMessage "Yes/No Box Results" "User selected No, exit status was $?"
    fi
}


time_out=3
function passwordDemo() {
    	PASSWORD=$(whiptail --title "Enter Password" --passwordbox "Please enter your secret password" 8 78 3>&1 1>&2 2>&3)
	read line < /opt/tfw/pwd.txt
        pwd=$( base64 -d <<< "$line" )
	#displayMessage "Password Box Results" "Your password file is $line"
	is_null=0
	if [ ! -n "$pwd" ]; then
		let is_null=1
	fi
        if [ ! -n "$PASSWORD" ]; then
               let is_null=1
        fi

	if [ "$is_null" == "1" ]; then
		sleep 1
	else
	    if [ "$pwd" == "$PASSWORD" ]; then
	        let need_password=0
	    else
    	     displayMessage "Password Box Results" "Your password is not right"
	     sleep $time_out
	     let time_out=$time_out*$time_out 
	    fi
	fi
}

function enter_shell() {
    /bin/bash
}

function textBoxDemo() {
    whiptail --textbox sample.txt 12 80 --scrolltext
}


function menuDemo() {
    displayMessage "Menu Box Results" "You were indeed looking at one!"

}

function checkListDemo() {
    TOPPINGS=$(whiptail --title "Check list Demo" --checklist \
        "Choose your toppings:" 20 78 8 \
            "PINEAPPLE" "Pineapple" ON \
            "JALAPENO" "Jalapenõ" OFF \
            "OLIVES" "Olives" ON \
            "MUSHROOMS" "Mushrooms" OFF \
            3>&1 1>&2 2>&3)

    displayMessage "Checklist Results" "You selected ${TOPPINGS}"

}

function radioListDemo() {
    TOPPINGS=$(whiptail --title "Check list Demo" --radiolist \
        "Choose your toppings:" 20 78 8 \
            "PINEAPPLE" "Pineapple" ON \
            "JALAPENO" "Jalapenõ" OFF \
            "OLIVES" "Olives" OFF \
            "MUSHROOMS" "Mushrooms" OFF \
            3>&1 1>&2 2>&3)

    displayMessage "Checklist Results" "You selected ${TOPPINGS}"

}

function progressGuageDemo() {
    {
        for ((i = 0 ; i <= 100 ; i+=5)); do
            sleep 0.1
            echo $i
        done
    } | whiptail --gauge "Please wait while we are sleeping..." 6 50 0

}

main








#whiptail --title "Check list example" --checklist \
#"Choose user's permissions" 20 78 4 \
#"NET_OUTBOUND" "Allow connections to other hosts" ON \
#"NET_INBOUND" "Allow connections from other hosts" OFF \
#"LOCAL_MOUNT" "Allow mounting of local devices" OFF \
#"REMOTE_MOUNT" "Allow mounting of remote devices" OFF
#
#
#{
#    for ((i = 0 ; i <= 100 ; i+=5)); do
#        sleep .1
#        echo $i
#    done
#} | whiptail --gauge "Please wait while we are sleeping..." 6 50 0
